package com.bc.plugin.doc.builder;

import com.bc.plugin.doc.base.*;
import com.bc.plugin.doc.base.impl.*;
import com.bc.plugin.doc.filter.IControllerFilter;
import com.bc.plugin.doc.filter.impl.ControllerAnnotationFilter;
import com.bc.plugin.doc.resolver.IApiParamHandle;
import com.bc.plugin.doc.resolver.param.AnnotationApiParamHandle;
import com.bc.plugin.doc.resolver.param.CustomRespFieldApiParamHandle;
import com.power.common.util.StringUtil;
import com.power.doc.constants.DocGlobalConstants;
import com.power.doc.constants.DocLanguage;
import com.power.doc.model.ApiConfig;
import com.power.doc.model.SourceCodePath;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xhh
 */
@Data
public class BuilderConfig {
    private IRequestMappingHandler requestMappingHandler;
    private IRequestHeaderHandler requestHeaderHandler;
    private BaseRequestParamHandler requestParamHandler;
    private BaseResponseParamHandler responseParamHandler;
    private BaseUsageDataHandler usageDataHandler;
    private boolean createUsageData;
    private JavaClassFileBuilder javaClassFileBuilder;
    private final List<IApiParamHandle> apiParamHandles = new ArrayList<>();
    private final List<IControllerFilter> controllerFilters = new ArrayList<>();

    public BuilderConfig() {
        requestMappingHandler = new DefaultRequestMappingHandler();
        requestHeaderHandler = new DefaultRequestHeaderHandler();
        requestParamHandler = new DefaultRequestParamHandler();
        responseParamHandler = new DefaultResponseParamHandler();
        usageDataHandler = new DefaultUsageDataHandler();
        controllerFilters.add(new ControllerAnnotationFilter());
        apiParamHandles.add(new AnnotationApiParamHandle());
        apiParamHandles.add(new CustomRespFieldApiParamHandle());
        createUsageData = true;
    }

    public void initData(ApiConfig config) {
        if (null == config) {
            throw new NullPointerException("ApiConfig can't be null");
        }
        if (StringUtil.isEmpty(config.getOutPath())) {
            throw new RuntimeException("doc output path can't be null or empty");
        }
        if (null != config.getLanguage()) {
            System.setProperty(DocGlobalConstants.DOC_LANGUAGE, config.getLanguage().getCode());
        } else {
            //default is chinese
            System.setProperty(DocGlobalConstants.DOC_LANGUAGE, DocLanguage.CHINESE.getCode());
        }
        if (javaClassFileBuilder == null) {
            List<String> pathList = null;
            if (config.getSourceCodePaths() != null) {
                pathList = config.getSourceCodePaths().stream().map(SourceCodePath::getPath).collect(Collectors.toList());
            }
            javaClassFileBuilder = new JavaClassFileBuilder(pathList);
        }
        for (IApiParamHandle apiParamHandle : apiParamHandles) {
            apiParamHandle.init(config, this);
        }
    }
}
